from dataclasses import dataclass
from typing import Dict, Literal, Union, List, Iterable

CorpusItem = Dict[Literal["corpus_id", "score", "text"], Union[int, float, str]]


@dataclass
class CorpusResult:
    corpus_id: int
    score: float
    text: str

    @classmethod
    def from_dict(cls, data: CorpusItem) -> "CorpusResult":
        return cls(
            corpus_id=int(data["corpus_id"]),
            # 将score 保留2位小数
            score=round(float(data["score"]), 2),
            text=str(data["text"])
        )

    @staticmethod
    def from_list(data: Iterable[CorpusItem]) -> List["CorpusResult"]:
        """从字典列表批量创建实例"""
        return [CorpusResult.from_dict(item) for item in data]
